package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.example.mapper.master.BookMapper;
import com.example.model.Book;
import com.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author long
 * @date 2025/4/28 11:31
 */
@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Book getBookByIdHash(String id) {
        // 尝试从Redis缓存中获取书籍
        Map<String,Object> cachedBookMap = redisTemplate.opsForHash().entries(id);
        if (MapUtil.isNotEmpty(cachedBookMap)) {
            return BeanUtil.toBean(cachedBookMap,Book.class);
        }

        // 如果缓存中没有，从数据库查询
        Book book = bookMapper.selectById(id);
        if (book != null) {
            // 将查询结果放入缓存，设置过期时间为10分钟
            Map<String, Object> bookMap = BeanUtil.beanToMap(book);
            redisTemplate.opsForHash().putAll(id,bookMap);
            redisTemplate.expire(id,10, TimeUnit.MINUTES);
        }
        return book;
    }

    @Override
    public Book getBookByIdStr(String id) {
        // 尝试从Redis缓存中获取书籍
        String cachedBook = (String)redisTemplate.opsForValue().get(id);
        if (StrUtil.isNotBlank(cachedBook)) {
            return JSON.parseObject(cachedBook,Book.class);
        }

        // 如果缓存中没有，从数据库查询
        Book book = bookMapper.selectById(id);
        if (book != null) {
            // 将查询结果放入缓存，设置过期时间为10分钟
            cachedBook = JSON.toJSONString(book);
            redisTemplate.opsForValue().set(id, cachedBook, 10, TimeUnit.MINUTES);
        }
        return book;
    }

}
